import React, { FC, useEffect } from 'react'
import ReactDOM, { findDOMNode } from 'react-dom'
import { IPositionProps } from './interface'
import './index.less'

// 盛放下拉面板的容器 DIV
let instance: HTMLDivElement;

const Position: FC<IPositionProps> = ({
    targetRef,
    children,
    onClose,
}) => {
    if (!instance) {
        instance = document.createElement('div')
        instance.className = 'position'
        document.body.appendChild(instance)
    }

    const onClickOutsize = (e: any) => {
        const result = findDOMNode(instance)?.contains(e.target)
        if (!result) {
            instance.style.top = '0px'
            onClose()
        }
    }

    useEffect(() => {
        document.addEventListener('mousedown', (e) => onClickOutsize(e), false)
        return () => {
            document.removeEventListener('mousedown', (e) => onClickOutsize(e), false)
        }
    }, [])

    useEffect(() => {
        function setInstanceStyle() {
            const { top, left, height } = targetRef.current.getBoundingClientRect();
            const style = {
                top: document.documentElement.scrollTop + top + height + 10 + 'px',
                left: document.documentElement.scrollLeft + left + 'px'
            }

            instance.style.top = style.top;
            instance.style.left = style.left;

            return { top, left, height }
        }

        setInstanceStyle();
    }, [targetRef])

    return instance && ReactDOM.createPortal(children, instance)
}

export default Position